package com.future;

import com.future.util.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: 129. 求根节点到叶节点数字之和
 *
 * @author weiruibai.vendor
 * Date: 2022/12/26 16:29
 */
public class Solution_129 {

    static Solution_129 instance = new Solution_129();

    public static void main(String[] args) {

        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        System.out.println(instance.sumNumbers(root));
    }

    public int sumNumbers(TreeNode root) {
        int ans = 0;
        List<Integer> list = new ArrayList<>();
        process(root, 0, list);
        for (Integer num : list) {
            ans += num;
        }
        return ans;
    }

    private void process(TreeNode root, int sum, List<Integer> ans) {
        if (root == null) {
            // 不能在这里收集，否则会重复收集
            return;
        }
        sum = sum * 10 + root.val;
        /**
         * 判断是叶子节点就收集
         */
        if (root.right == null && root.left == null) {
            ans.add(sum);
            return;
        }
        process(root.left, sum, ans);
        process(root.right, sum, ans);
    }
}
